<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="700px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./payWay.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { savePayWay, getPayWay } from "/@/api/pay"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const rowId = ref("")
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter })
    isUpdate.value = !!data?.isUpdate
    if (unref(isUpdate)) {
      rowId.value = data.record.mchNo
    }
    const payWay = await getPayWay({ wayCode: data.record.wayCode })

    // 无论新增还是编辑，都可以设置表单值
    if (typeof payWay === "object") {
      setFieldsValue({
        ...payWay,
      })
    }
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter })
  })
  const getTitle = computed(() => (!unref(isUpdate) ? "新增支付方式" : "编辑支付方式"))

  async function handleSubmit() {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })
      await savePayWay(values, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success", { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } })
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
